package com.geek.novel.utils

import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.collections.ArrayList


/**
 * 日期工具类
 */
object DateUtil {

    private const val defaultDateFormat: String = "yyyy-MM-dd HH:mm:ss"

    fun formatDate(date: Date?): String?{
        return formatDate(date, defaultDateFormat)
    }

    fun formatDate(date: Date?, pattern: String): String? {
        if(date == null){
            return null
        }
        val format = SimpleDateFormat(pattern, Locale("zh", "CN"))
        return format.format(date);
    }

    /**获取当前时间：时分*/
    fun getCurrentDate(pattern: String="yyyy-MM-dd"): String{
        return formatDate(Date(), pattern)!!
    }

    /**获取当前时间：时分*/
    fun getCurrentTime(pattern: String="HH:mm"): String{
        return formatDate(Date(), pattern)!!
    }

	/**
	 * 判断是否在时间段内(分钟)
	 * @param limit 限制
	 */
	fun isTimeInMinutes(date: Date?, limit: Long): Boolean{
		return isTimeIn(date, limit, TimeUnit.MINUTES)
	}
	
	/**
	 * 判断是否在时间段内
	 * @param limit 限制
	 */
	fun isTimeIn(date: Date?, limit: Long, unit: TimeUnit): Boolean{
		if(date == null){
			return false
		}
		val time = System.currentTimeMillis() - date.time
		val timeLimit = unit.toMillis(limit)
		
		return time <= timeLimit
	}


	/**获取最近N天的数组，包括今天*/
	fun getLatestDaysArray(n: Int, format: String): List<String>{
		val array = ArrayList<String>()
		for(i in 1..n){
			val date = beforeAfterDate(i-n)
			val dateStr = formatDate(date, format)
			array.add(dateStr!!)
		}
		return array
	}

	/**获取最近N天*/
	fun beforeAfterDate(days: Int): Date{
		val nowTime = System.currentTimeMillis()
		val changeTimes = days * 24L * 60 * 60 * 1000
		return Date(nowTime + changeTimes)
	}

}